<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Cache;

class Base extends \app\base\controller\Base
{
	public function _initialize()
    {
    	//菜单 
    	/* $menus = Cache::remember('menus',function(){
			$list = Db::name('menu')->where('state',1)->select();
			$menu = Arr2Tree($list);
			return $menu;
		}); */
		//登录
		$this->isLogin();
		
		$list = Db::name('menu')->whereIn('id',$this->user['menus'])->where('state',1)->whereNull('delete_time')->select();
		$menus = Arr2Tree($list);
		
		if($this->user['user_id'] == 6){
			$menus = array_slice($menus,0,2);
		}
        
        //日记（POST）
        $request  =  request();
        if($request->isPost() && strtolower($request->controller()) != 'login') {
            
            $log = [
                'router' => strtolower($request->module().'-'.$request->controller().'-'.$request->action()),
                'data' => json_encode(input('post.')),
            ];
            $this->_log($log);
            
        }
    	
		$this->assign('menus', $menus);
        //
        $action = in_array(request()->action(),['add','edit']) ? 'index' : request()->action();
		$this->assign('menu_current', strtolower('/'.request()->module().'/'.request()->controller().'/'.$action)  );
		$this->assign('static_dir', '');
		$this->assign('notPopup', 1);
		$this->assign('list', [ ['test'=>'testvalue'] ]);
        $this->assign('local', file_exists(ROOT_PATH .'./.local'));
		
    }
    
    //列表
    public function index() {
		
		$where = $this->search();
		//列表
		$list = $this->joins()->where($where)->where('m.delete_time',$where['m.delete_time'])->order($this->id.' DESC')->fetchSql(0)->paginate(10,false,[
		'query' => input('param.')
		]);
		
		$this->assign('list',$list);
		$this->assign('pager',$list->render());
		
		//弹出层搜索
		$this->_op();
		
		return $this->out();
		
	}
    
    //检查登录
    protected function isLogin() {
		
		$this->uid = StrDecrypt(cookie('user_id'));
		
		if(!$this->uid && request()->controller() != 'Login') {
			return $this->redirect('login/index');
		}
		
		$this->user = Db::name('user')->alias('u')->join('role r','u.role_id = r.role_id')
					  ->where('user_id',$this->uid)->find();
					  
//		halt($this->user);
		//菜单
		$this->user['menus'] = explode(',',$this->user['menus']);
		//公务
		$this->user['official'] = in_array($this->user['role_id'],config('base.official_role'));
		
	}
	
	protected function _op() {
		$op = input('param.op');
		if(in_array($op, ['search','bind','unbind','entrust']) ) {
			$this->assign('notPopup',0);
		}
		$this->assign('op',$op);
	}
	
	//搜索
	protected function search() {
		//搜索
		$where = $options = [];
		$P = input('param.');
		if($P) {
			foreach($P AS $key=>$val) {
				
				if( $val && !in_array($key, ['op','page','filter']) ){
					
					if(StrFind($key,'-')) {
						$keys = explode('-',$key);
						$wkey = $keys[0].'.'.$keys[1];
						$key = $keys[1];
					} else {
						$wkey = 'm.'.$key;
					}
					
					if($key == 'start_date'){
						$where[$wkey] = ['>=',$val];
					} elseif($key =='end_date'){
						$where[$wkey] = ['<=',$val];
					} elseif( in_array($key, ['name','number','phone','order_no','insurance_company']) ) {
						$where[$wkey] = ['LIKE','%'.$val.'%'];
					} elseif( StrFind($key,'_time') ) {
						$where[$wkey] = $val;
					} else {
						$where[$wkey] = $val;
					}
					
					$options[$key] = $where[$wkey];
				}
                
                if($key == 'filter') {
                    $where['m.delete_time'] = ['>',0];
                }
                
			}
		}
		$this->options($options);
		return $where;
		
	}
    
    public function detail() {
		
		$id = input('param.'.$this->id);
		$item = $this->joins()->where('m.'.$this->id,$id)->find();
		
		$item = $this->options($item);

		$this->assign('item',$item);
		$this->_op();
		return $this->out();
		
	}
	
    public function read() {
		
		$id = input('param.'.$this->id);
		$item = $this->joins()->where('m.'.$this->id,$id)->find();
		$item = $this->options($item);
		return $this->apiout($item);
		
	}
	
//	//添加
//	public function add() {
//		
//		if(request()->.00()) {
//			
//			$data = $this->data();
//			$id = Db::name($this->table)->insertGetId($data);
//			
//			//更新缓存
//			return $this->res($id?1:0 ,[ 'msg' => '','data'=>$id],'index');
//		}
//		//选项 
//		$this->options();
//		
//		return $this->out();
//		
//	}
//	
//	public function edit() {
//		
//		$id = input('param.'.$this->id.'/d');
//		
//		if(!$id) {
//			return $this->error('入口非法，请重试');
//		}
//		//提交
//		if(request()->isPost()) {
//			
//			$data = $this->data();
//			$rslt = Db::name($this->table)->where($this->id,$id)->update($data);
//				
//			return $this->res($rslt,['修改并保存成功','内容未修改或网络问题，请联系开发者 i@fazi.me'],1);
//			
//		}
//		//连接查询
//		$item = $this->joins()->where($this->id,$id)->find();
//		
//		//选项
//		$item = $this->options($item);
//		$this->assign('item',$item);
//		
//		return $this->out('add');
//		
//	}
//	
//	//删除 
//	public function delete() {
//		
//		$id = input('post.id/a');
//		
//		if($id) {
//			if(is_array($id)) $id = implode(',',$id);
//			$rslt = Db::name($this->table)->whereIn($this->id,$id)->setField('delete_time',time());
//		}
//		
//		return $this->res($rslt);
//		
//	}
	
	//状态 
	public function state() {
		
		$id = input('post.id/d');
		$state = input('post.state/d');
		
		if($id) {
			$key = $this->state ?: 'state';
			$rslt = Db::name($this->table)->where($this->id,$id)->fetchSql(0)->setField($key,$state);
		}
		
		return $this->res($rslt);
		
	}
	
	
	//上传
	protected function upload($data){
		
    	// 获取表单上传文件
	    $files = request()->file();
	    if($files){
		    foreach($files as $name => $file){
		        // 移动到框架应用根目录/public/uploads/ 目录下
		        $info = $file->move(UPLOAD_PATH);
		        if($info){
		            // 成功上传后 获取上传信息
		            // 输出 42a79759f284b767dfcb2a0197904287.jpg
		            $data[$name] = $info->getSaveName(); 
		        }else{
		            // 上传失败获取错误信息
	//	            echo $file->getError();
		        }    
		    }
	    }
	    return $data;
	}
	
	//更新缓存
	protected function clearcache($rslt) {
		if($rslt) Cache::rm($this->table);
	}
	
	//DATA
	protected function data() {
		$P = input('post.');
		
		//ID
		if( isset($P['id']) ) {
			$P[$this->id] = $P['id'];
			unset($P['id']);
		}
		//数据整理
		$P = array_map('Arr2Set',$P);
		$this->validData( $P );#验证
		$data = $this->parseData( $P );
		
		//数组值变SET
		if($data[$this->id]) {
			
		} else {
			unset($data[$this->id]);
		}
		//上传图片
		$data = $this->upload($data);
		
		return $data;
	}
	
	protected function validData($data = []) {
		return true;
	}
	protected function parseData($data = []) {
		return $data;
	}
	
	protected function options($item = []) {
		return $item;
	}
	protected function _log($log = []) {
        $log['user_id'] = $this->uid;
        $log['ip'] = request()->ip();
		return Db::name('UserLog')->exp('datetime','now()')->insert($log);
	}
	
	
	protected function CF($url,$postdata = [],$isZip = 0) {
		
		ob_start();
		$hander = curl_init();
		curl_setopt($hander, CURLOPT_HTTPHEADER , $headerArr );
		curl_setopt($hander, CURLOPT_URL,$url); 
		curl_setopt($hander, CURLOPT_FOLLOWLOCATION,1); 
		curl_setopt($hander, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

		if ($postdata) {
			curl_setopt( $hander, CURLOPT_POST, 1 );
			curl_setopt( $hander, CURLOPT_POSTFIELDS, is_array($postdata) ? http_build_query($postdata) : $postdata );
		} else {
			curl_setopt( $hander, CURLOPT_CUSTOMREQUEST, 'GET');
		}

		curl_setopt($hander, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
	    curl_setopt($hander, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在 
		$isZip && curl_setopt($hander, CURLOPT_ENCODING, "gzip");
		curl_setopt($hander, CURLOPT_HEADER,0);
//		curl_setopt($hander, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8')); //构造IP
		curl_setopt($hander, CURLOPT_RETURNTRANSFER,1);//以数据流的方式返回数据,当为false是直接显示出来
		
		curl_setopt($hander,CURLOPT_TIMEOUT,60);
		curl_setopt($hander,CURLOPT_CONNECTTIMEOUT,60);
		$content = curl_exec($hander);
		$info = curl_getinfo($hander);
//		halt($content);
	
//		curl_close($hander);
		$rslt = [$content,$info];
//		halt($rslt);
		Return $rslt;
	}

	/**
	 * 成功返回
	 */
	public function retSucc($data=array(),$msg='ok',$code=1){
		$info['code'] = $code;
		$info['msg']  = $msg;
		$info['time'] = time();
		$info         = array_merge($info,$data);
		return json($info);
	}

	/**
	 * 失败返回
	 */
	public function retError($msg='',$code=0){
		$info['code'] = $code;
		$info['msg']  = intval($msg)>99 ? $this->getErrorMsg($msg) : $msg;
		$info['time'] = time();
		trace($msg,'apiError');
		return json($info);
	}

	/**
	 * 全部返回
	 * @param int $code
	 * @param string $msg
	 * @param int $type
	 * @return mixed
	 */
	public function retAll($code=1,$msg='',$type=0){
		if($code==1){
			if(is_array($msg)){
				if($type==0){
					return $this->retSucc(['data'=>$msg]);
				}else{
					return $this->retSucc($msg);
				}
			}else{
				return $this->retSucc();
			}
		}else{
			return $this->retError($msg);
		}
	}

	/**
	 * 错误信息代码转换
	 * @param int $code
	 * @return string
	 */
	public function getErrorMsg($code=100){
        \think\Config::set(include  APP_PATH.'/../config/api/config.php','api');
		$errorArr = \think\Config::get('api.error_msg');
		if(intval($code)==0){
			return $code;
		}

		return isset($errorArr[$code]) ? $errorArr[$code] : 'undefine';
	}
	
}
